// pages/mine/find/answer/index/index.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animation: ['', '', '', ''],
    countDownNum: 20,
    timer: '',
    ans: [],
    question: "",
    que: [],
    que_index: 0,
    user_sel: false,
    que_num:8,//题目数量

    is_rest:false,
  },
  //获取题库
  get_que() {
    var that = this
    var flag=false;
    wx.request({
      url: app.globalData.url + 'question/' + that.data.que_num, // 仅为示例，并非真实的接口地址
      data: {},
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log("------获取题库------")
        console.log(res.data.data)

        that.setData({
          que: res.data.data
        })
        that.init_que()
        wx.hideToast()
      },
      fail(res){
        console.log(res)
        wx.showModal({
          title: '提示',
          content: '接口请求错误，是否重新加载',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.onLoad()
            } else {
              console.log('用户点击取消')
              wx.switchTab({
                url: '../answer'
              })
            }
          },
        })
      }
    })
  },
  //初始化题目,跳转下一题
  init_que() {
    var that = this
    console.log('------得分------')
    console.log(app.globalData.score)
    if (that.data.que_index>=that.data.que_num){
      //console.log(app.globalData.score)
      //that.updateScore()
      wx.navigateTo({
        url: '../rank/rank',
      })
    }
    if (that.data.timer) clearInterval(that.data.timer);
    var index = that.data.que_index
    var que = that.data.que[index]
    var an = [{
        answer: que.answer0,
        is_ans: true,
        is_sel: false
      },
      {
        answer: que.answer1,
        is_ans: false,
        is_sel: false
      },
      {
        answer: que.answer2,
        is_ans: false,
        is_sel: false
      },
      {
        answer: que.answer3,
        is_ans: false,
        is_sel: false
      }
    ]
    console.log("----排序后----")
    var shuffle = [0, 1, 2, 3].sort(function() {
      return 0.5 - Math.random()
    })
    //console.log(shuffle)
    //console.log([an[shuffle[0]], an[shuffle[1]], an[shuffle[2]], an[shuffle[3]]])
    that.setData({
      countDownNum: 20,
      ans: [an[shuffle[0]], an[shuffle[1]], an[shuffle[2]], an[shuffle[3]]],
      que_index: index + 1,
      question: que.question,
      user_sel: false
    })
    that.countDown()
  },
  //答题
  toggle(e) {
    var that = this;
    console.log(e);
    if (that.data.user_sel) return
    var index = e.currentTarget.dataset.id
    var ani = that.data.animation
    var an = that.data.ans
    an[index].is_sel = true
    //答案错误
    if (an[index].is_ans == false)
    {
      ani[index] = 'shake'
      app.globalData.score -= 1;
      for (var i = 0; i < 4; i++) {
        if (an[i].is_ans == true) {
          an[i].is_sel = true
          break
        }
      }
    }
    else
    {
      ani[index] = 'fade'
     
      app.globalData.score +=2;
    }    
    console.log(ani);
    that.setData({
      animation: ani,
      ans: an,
      user_sel: true
    })
    ani[index] = ''
    clearInterval(that.data.timer);
    setTimeout(function() {
      that.setData({
        animation: ani
      })
      that.init_que()
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //上传分数
  updateScore(){
    console.log('------上传分数------')
    if (app.globalData.score!=0)
    {
      wx.request({
        url: app.globalData.url + 'rank', // 仅为示例，并非真实的接口地址
        data: {
          user_id:app.globalData.user_id,
          score:app.globalData.score,
        },
        method: "POST",
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data)
          if(res.data.state)app.globalData.score=0
        }
      })

    }
  },
  //倒计时
  countDown: function() {
    let that = this;
    let countDownNum = that.data.countDownNum; //获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      timer: setInterval(function() { //这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum--;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum == 0) {
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timer);
          that.init_que()
          //关闭定时器之后，可作其他处理codes go here
        }
      }, 1000)
    })
  },
  onLoad: function(options) {
    app.globalData.score = 0
    if(!app.globalData.user_id){
      wx.switchTab({
        url: '../answer',   //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
      })
    }
    var that = this
    that.get_que()
    wx.showToast({
      title: "题库下载中...",
      icon: 'loading',
      duration: 1000,
      mask: true
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '答题知校史，自信商大人',
      path: 'pages/mine/find/answer/answer',
      imageUrl: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/7JipVadPBsDOe3brKK.GDj3o1DKQogLMHj9.o7B*1ak!/b/dFABAAAAAAAA&bo=AAUABAAFAAQDByI!&rf=viewer_4' //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。
    }
  }
})